#!/bin/sh

#
# Test that a small FAT filesystem gets created in a way that's
# compatible with the TI AM335x ROM bootloader. This means that
# there's always a redundant FAT. The FATFS code doesn't create
# a redundant FAT by default, so this catches the case where it
# isn't enabled when upgrading the library.
#
# U-Boot requires that the type be set to "FAT16" rather than
# just "FAT", so that's checked here as well.

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 16321)

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

EXPECTED_OUTPUT=$WORK/expected.out
ACTUAL_OUTPUT=$WORK/actual.out

# This is the expected first block of the FAT entry
# The key location to verify is offset 0x10. It should
# be "2" to indicate a redundant FAT. Also note the type
# is "FAT16".
base64_decode >$EXPECTED_OUTPUT <<EOF
6/6QTVNET1M1LjAAAgEBAAIAAsE/+EAAPwD/AAAAAAAAAAAAgAApwT8hAE5PIE5BTUUgICAgRkFUMT
YgICAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVao=
EOF

dd if=$IMGFILE skip=63 count=1 2>/dev/null >$ACTUAL_OUTPUT
diff $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check the FAT file format using fsck
dd if=$WORK/fwup.img skip=63 of=$WORK/vfat.img
$FSCK_FAT $WORK/vfat.img
